import React, { useCallback, useEffect, useRef, useState } from 'react';
import classNames from 'classnames';

/**
*@deprecated
 * 一个最简单的拖拽功能实现
 * 理论知识来自  前端/css/拖拽功能实现
*
* */
const dragDrop: React.FC = props => {
  const [position,setPosition] = useState({x:0,y:0});
  const obj = useRef({
    dragIng:false,
    mouseStartX:0,
    mouseStartY:0,
    dragDomStartX:0,
    dragDomStartY:0,
  });
  const containerDom = useRef(null);
  /**
  * @待拖拽的元素
  * */
  const dragDom = useRef(document.createElement('div'));

  const onMouseMove = useCallback((e)=>{
    if (obj.current.dragIng){
    /**
     * @deprecated
    * 元素y = 现在鼠标y - 原来鼠标y + 原来元素y
     元素x = 现在鼠标x - 原来鼠标x + 原来元素x
    * */
      const x:number = e.x - obj.current.mouseStartX + obj.current.dragDomStartX;
      const y:number = e.y - obj.current.mouseStartY + obj.current.dragDomStartY;
      setPosition({x,y});
    }
  },[dragDom]);

  const onMouseUp = useCallback(()=>{
    obj.current.dragIng = false;
    window.removeEventListener('mousemove', onMouseMove);
    window.removeEventListener('mouseup', onMouseUp);
  },[]);

  const onMouseDown = useCallback((e)=>{
    obj.current.dragIng = true;
    obj.current.mouseStartX =e.nativeEvent.x;
    obj.current.mouseStartY =e.nativeEvent.y;
    obj.current.dragDomStartX =dragDom.current.offsetLeft;
    obj.current.dragDomStartY =dragDom.current.offsetTop;
    console.log(e.nativeEvent,1);
    window.addEventListener('mousemove', onMouseMove);
    window.addEventListener('mouseup', onMouseUp);
  },[obj]);

  return (
    <div ref={containerDom} style={{
      width:400,
      height:400,
      position:'relative',
      background:'#e8e8e8'
    }}>
      <div ref={dragDom} onMouseDown={onMouseDown} style={{
        width:30,
        height:30,
        position:'absolute',
        top:position.y,
        left:position.x,
        background:'red'
      }}>可拖动</div>
    </div>
  );
};

export default dragDrop;
